package com.quasar.hpatient.module.home_urinevolume;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home_inspection.CalendarBean;
import com.quasar.hpatient.bean.home_inspection.CalendarULBean;
import com.quasar.hpatient.bean.home_urinevolume.UrinevolumeItemBean;
import com.quasar.hpatient.dialog.CalendarDialog;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.DimenUtil;
import lib.quasar.widget.chart.ChartView;
import okhttp3.RequestBody;

/**
 * description: 首页 ==> 出入量
 * created by kalu on 2018/4/25 9:23
 */
public final class UrinevolumePresenter implements BasePresenter {

    private final LinkedList<UrinevolumeItemBean> mDatas = new LinkedList();

    void initTime(final UrinevolumeView view, TextView dates, TextView times) {

        if (null != dates) {
            view.setText(dates, getCalendar());
        }
        if (null != times) {
            view.setText(times, getMinuteLittle());
        }
    }

    void initList(final UrinevolumeView view, RecyclerView recycler, boolean mulit) {

        if (null == view || null == recycler) return;

        final BaseCommonAdapter<UrinevolumeItemBean> adapter = new BaseCommonAdapter<UrinevolumeItemBean>(mDatas, R.layout.activity_home_urinevolume_child) {

            @Override
            protected void onNext(final RecyclerHolder holder, final UrinevolumeItemBean model, final int position) {

                view.setText(holder, R.id.activity_home_urinevolume_child_time, model.getLogtime(!mulit));
                view.setText(holder, R.id.activity_home_urinevolume_child_type, model.getRecord_name());
                view.setText(holder, R.id.activity_home_urinevolume_child_input, model.getRecord_value());

                holder.setOnClickListener(R.id.activity_home_urinevolume_child_input, v -> {
                    final String value = model.getRecord_value();
                    final String name = model.getRecord_name();
                    view.showInput(value, name, position);
                });
                holder.setOnLongClickListener(v -> {
                            view.showDelete(model.getRecord_name(), position);
                            return true;
                        }, R.id.activity_home_urinevolume_child_time,
                        R.id.activity_home_urinevolume_child_type,
                        R.id.activity_home_urinevolume_child_input);
            }
        };

        RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(40));
        View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_urinevolume_head, null);
        head.setLayoutParams(params);
        adapter.addHead(head);

        // adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    final void schemelList(CalendarDialog dialog, String year, String month, String minDay, String maxDay) {

        final HashMap<String, Object> map = new HashMap<>();
        map.put(BEGIN_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, minDay));
        map.put(END_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, maxDay));
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_URINEVOLUME);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_9);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().schemeULList(params);

        request(observable, new OnModelAcceptChangeListener<List<CalendarULBean>>() {
            @Override
            public void modelSucc(List<CalendarULBean> list) {
                dialog.getCalendarView().setScheme(list);
            }
        });
    }

    void urinevolumeList(final UrinevolumeView view, RecyclerView recycler, ChartView chart, TextView dates, boolean mulit) {

        if (null == view || null == recycler || null == chart || null == dates) return;

        final String trim = dates.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            view.toast("时间格式不正确");
            return;
        }

        mDatas.clear();

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.RECORD_DATE, view.getDate());
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_URINEVOLUME);

        if (mulit) {

            map.put(HttpParams.NUM, "10");
            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_3);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().urinevolumeListMulit(params);

            request(observable, new OnModelAcceptChangeListener<List<HashMap<String, ArrayList<UrinevolumeItemBean>>>>() {
                @Override
                public void modelFail() {
                    view.setChartNull(chart, R.string.chart_null);
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(List<HashMap<String, ArrayList<UrinevolumeItemBean>>> result) {

                    if (null == result || result.size() == 0) {
                        modelFail();
                        return;
                    }

                    for (HashMap<String, ArrayList<UrinevolumeItemBean>> map : result) {

                        if (null == map || map.size() == 0) continue;

                        final Collection<ArrayList<UrinevolumeItemBean>> collection = map.values();
                        if (null == collection || collection.size() == 0) continue;

                        for (ArrayList<UrinevolumeItemBean> list : collection) {
                            if (collection.size() == 1 && (null == list || list.size() == 0))
                                continue;

                            for (UrinevolumeItemBean model : list) {

                                if (collection.size() == 1 && list.size() == 1 && null == model)
                                    continue;
                                mDatas.add(model);
                            }
                        }
                        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                    }
                }


                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });

        } else {

            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_2);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().urinevolumeList(params);

            request(observable, new OnModelAcceptChangeListener<HashMap<String, ArrayList<UrinevolumeItemBean>>>() {
                @Override
                public void modelFail() {
                    view.setChartNull();
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(HashMap<String, ArrayList<UrinevolumeItemBean>> result) {

                    if (null == result) {
                        modelFail();
                        return;
                    }

                    final Collection<ArrayList<UrinevolumeItemBean>> collection = result.values();
                    if (null == collection || collection.size() == 0) {
                        modelFail();
                        return;
                    }

                    for (ArrayList<UrinevolumeItemBean> list : collection) {

                        if (collection.size() == 1 && (null == list || list.size() == 0)) {
                            modelFail();
                            return;
                        }

                        for (UrinevolumeItemBean model : list) {

                            if (collection.size() == 1 && list.size() == 1 && null == model) {
                                modelFail();
                                return;
                            }
                            mDatas.add(model);
                        }
                    }
                    Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                }


                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });
        }
    }

    void saveUrinevolume(UrinevolumeView view, ChartView chart, RecyclerView recycler, EditText edit) {

        if (null == view || null == chart || null == recycler || null == edit)
            return;

        final String dateStr = view.getDate();
        if (TextUtils.isEmpty(dateStr)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String timeStr = view.getTime();
        if (TextUtils.isEmpty(timeStr)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String name = view.getName();
        if (TextUtils.isEmpty(name)) {
            return;
        }

        final String input = view.getUrinevolume();
        if (TextUtils.isEmpty(input)) {
            return;
        }

        // step:1
        final HashMap<String, List<UrinevolumeItemBean>> map = new HashMap<>();
        final ArrayList<UrinevolumeItemBean> list = new ArrayList<>();
        // step:2
        final UrinevolumeItemBean news = new UrinevolumeItemBean();
        news.setRecord_name(name);
        news.setRecord_dose(BaseApp.getContext().getResources().getString(R.string.home_urinevolume_unit));
        news.setRecord_datetime(getDate(view.getDate(),timeStr));
        if ("入量".equals(name)) {
            news.setRecord_input(input);
        } else if ("白天尿量".equals(name)) {
            news.setRecord_output(input);
        } else {
            news.setRecord_night(input);
        }
        list.add(news);

        map.put(getDate(dateStr), list);
        // step:3
        String warnSign = "0";
        for (UrinevolumeItemBean model : mDatas) {

            final String key = model.getKey();
            if (map.containsKey(key)) {
                final List<UrinevolumeItemBean> list1 = map.get(key);
                list1.add(model);
            } else {
                final List<UrinevolumeItemBean> list2 = new ArrayList<>();
                list2.add(model);
                map.put(key, list2);
            }
        }
        mDatas.addFirst(news);
        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

        // step:4
        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(dateStr));
        params2.put(HttpParams.DATAS, map);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_URINEVOLUME);
        params2.put(HttpParams.WARN_SIGN, "0");

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveUrinevolume(params1);
        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                view.toast("添加出入量失败");
            }

            @Override
            public void modelSucc() {

                edit.getText().clear();
                edit.clearFocus();
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("添加出入量成功");
            }
        });
    }

    void modifyUrinevolume(final UrinevolumeView view, RecyclerView recycler, ChartView chart, String input, int position) {

        if (null == view || null == recycler || null == chart || position >= mDatas.size())
            return;

        if (TextUtils.isEmpty(input)) {
            return;
        }

        final UrinevolumeItemBean model = mDatas.get(position);
        final String old1 = model.getRecord_input();
        final String old2 = model.getRecord_output();
        final String old3 = model.getRecord_night();

        if (model.isInput()) {
            model.setRecord_input(input);
        } else if (model.isOutput()) {
            model.setRecord_output(input);
        } else {
            model.setRecord_night(input);
        }

        final HashMap<String, List<UrinevolumeItemBean>> push = new HashMap<>();
        push.put(getDate(view.getDate()), mDatas);

        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(view.getDate()));
        params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_URINEVOLUME);
        params2.put(HttpParams.WARN_SIGN, "0");

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveUrinevolume(params1);
        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                if (model.isInput()) {
                    model.setRecord_input(old1);
                } else if (model.isOutput()) {
                    model.setRecord_output(old2);
                } else {
                    model.setRecord_night(old3);
                }
                view.toast("修改出入量失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("修改出入量成功");
            }
        });
    }

    void deleteUrinevolume(final UrinevolumeView view, RecyclerView recycler, ChartView chart, int position) {

        if (null == view || null == recycler || null == chart || position >= mDatas.size())
            return;

        final UrinevolumeItemBean old = mDatas.get(position);
        mDatas.remove(position);

        final HashMap<String, List<UrinevolumeItemBean>> push = new HashMap<>();
        push.put(getDate(view.getDate()), mDatas);
        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(view.getDate()));
        if (mDatas.size() == 0)
            params2.put(HttpParams.DATAS, "");
        else
            params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_URINEVOLUME);
        params2.put(HttpParams.WARN_SIGN, "0");

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveUrinevolume(params1);
        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                mDatas.set(position, old);
                view.toast("删除出入量失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("删除出入量成功");
            }
        });
    }

    private final void checkBoundary(String in, String out, String night) {

        Context context = BaseApp.getContext();
        if (TextUtils.isEmpty(in)) {
            in = BaseConstant.ZERO;
        }

        if (TextUtils.isEmpty(out)) {
            out = BaseConstant.ZERO;
        }

        if (TextUtils.isEmpty(night)) {
            night = BaseConstant.ZERO;
        }
//
//        UrinevolumeItemBean chartModel = mDataChart.get(0);
//        String logvalue = chartModel.getRecord_value();
//        if (TextUtils.isEmpty(logvalue)) {
//            logvalue = BaseConstant.ZERO + File.separator + BaseConstant.ZERO + File.separator + BaseConstant.ZERO;
//        }
//        String[] news = logvalue.split(File.separator);
//        int in1;
//        if (TextUtils.isEmpty(news[0])) {
//            in1 = 0;
//        } else {
//            in1 = Integer.parseInt(news[0]);
//        }
//        int out1;
//        if (TextUtils.isEmpty(news[1])) {
//            out1 = 0;
//        } else {
//            out1 = Integer.parseInt(news[1]);
//        }
//        int night1;
//        if (TextUtils.isEmpty(news[2])) {
//            night1 = 0;
//        } else {
//            night1 = Integer.parseInt(news[2]);
//        }
//
//        final int in2 = Integer.parseInt(in) + in1;
//        if (in2 > 5000) {
//            ToastUtil.showToast(context.getResources().getString(R.string.home_urinevolume_warning_in));
//            return;
//        }
//
//        final int out2 = Integer.parseInt(out) + out1;
//        if (out2 > 5000) {
//            ToastUtil.showToast(context.getResources().getString(R.string.home_urinevolume_warning_out));
//            return;
//        }
//
//        final int night2 = Integer.parseInt(night) + night1;
//        if (night2 > out2) {
//            ToastUtil.showToast(context.getResources().getString(R.string.home_urinevolume_warning_night2));
//            return;
//        }
//        if (night2 > 5000) {
//            ToastUtil.showToast(context.getResources().getString(R.string.home_urinevolume_warning_night));
//            return;
//        }
    }

    private final void resetChart() {

//        UrinevolumeItemBean model2 = mDataChart.get(0);
//        model2.setLogvalue(BaseConstant.ZERO + File.separator + BaseConstant.ZERO + File.separator + BaseConstant.ZERO);
//
//        for (int i = 0; i < mDataList.size(); i++) {
//
//            UrinevolumeItemBean model1 = mDataList.get(i);
//            String logvalue1 = model1.getLogvalue();
//            String[] news = logvalue1.split(File.separator);
//            int in1 = Integer.parseInt(news[0]);
//            int out1 = Integer.parseInt(news[1]);
//            int night1 = Integer.parseInt(news[2]);
//
//            model2.setDailyitemdose(model1.getDailyitemdose());
//            model2.setDailyitemname(model1.getDailyitemname());
//            model2.setLogtime(model1.getLogtime());
//
//            String logvalue2 = model2.getLogvalue();
//            String[] old = logvalue2.split(File.separator);
//            int in = Integer.parseInt(old[0]) + in1;
//            int out = Integer.parseInt(old[1]) + out1;
//            int night = Integer.parseInt(old[2]) + night1;
//            model2.setLogvalue(in + File.separator + out + File.separator + night);
//        }
    }

    @Override
    public void recycler() {
    }
}
